﻿using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;

namespace CRM.Database.Model
{
    public static class DB
    {
        private static CRMEntities _crmEntities;


        private static List<v_Settlements> _VSettlements;

        /// <summary>
        /// 
        /// </summary>
        public static CRMEntities Entities
        {
            get
            {
                if (_crmEntities == null)
                {
                    _crmEntities = new CRMEntities();
                    _crmEntities.Configuration.AutoDetectChangesEnabled = false;
                }
                return _crmEntities;
            }
        }

        private static List<Products> _products;

        public static List<Products> Products
        {
            get
            {
                if(_products==null)
                {
                    var col = new ProductsCollection();
                    _products = col.ProductsList;

                }

                return _products;
            }
        } 

        /// <summary>
        /// Реальные обороты клиентов
        /// </summary>
        public static List<v_TrueTurnovers> TrueTurnovers
        {
            get
            {
               
                if (_trueTurnovers == null)
                {
                    _trueTurnovers = new List<v_TrueTurnovers>();

                    //var count = Entities.v_Turnovers.OrderBy(c=>c.IdTurnover).Skip(1000000).Take(100).Count();

                    //bool cont = true;
                    //int step = 0;
                    //int page = 1000;

                    //while(cont)
                    //{
                    //    var list = Entities.v_TrueTurnovers.OrderBy(c => c.IdTurnover).Skip(page*step).Take(page).ToList();
                    //   _trueTurnovers.AddRange(list);
                    //    step++;
                    //    if(list.Count==0)
                    //        cont = false;
                    //}
                    //{
                    //}

                       _trueTurnovers = Entities.v_TrueTurnovers.ToList();

//                    try
//                    {
//                        foreach(var item in  Entities.v_Turnovers.Where(c=>c.IdTurnoverClassification==1))
//                        {
//                            _trueTurnovers.Add(item);
//                        }

//                        foreach (var item in Entities.v_Turnovers.Where(c => c.IdTurnoverClassification == 2))
//                        {
//                            _trueTurnovers.Add(item);
//                        }

//                        var col = from turn in Entities.v_Turnovers
//                                  select
//                                      new {dealerNum = turn.DealerSequentalNumber, year = turn.Year, month = turn.Month};

//                        foreach (var item in Entities.v_Turnovers.Where(c => c.IdTurnoverClassification == 3))
//                        {
//                            //var dealerTurnover =
//                            //    Entities.v_Turnovers.FirstOrDefault(c => c.IdTurnoverClassification==1 & c.Year == item.Year & c.Month == item.Month & c.DealerSequentalNumber==item.ClientSequentalNumber);

//                            var dealerTurnover =
//                                col.FirstOrDefault(
//                                    c =>
//                                    c.dealerNum == item.ClientSequentalNumber & c.year == item.Year &
//                                    c.month == item.Month);
//                            if(dealerTurnover==null)
//                            _trueTurnovers.Add(item);
//                        }


////                        foreach (var item in col)
////                        {

////                        }

////                        //var col2 = Entities.v_TrueTurnovers;
////                        //foreach(var item in col2)
////                        //{

////                        //}
//////                        _trueTurnovers = DB.Entities.v_TrueTurnovers.Where(c=>c.Year==2013 ).ToList();
//                      //  _trueTurnovers = Entities.v_TrueTurnovers.AsNoTracking().Where(c=>c.Year==2013).ToList();



//                        _trueTurnovers = _trueTurnovers.OrderBy(c => c.IdTurnover).ToList();
//                    }
//                    catch
//                    {
//                    }
                }
               

                return _trueTurnovers;
            }
        }

        private static List<v_TrueTurnovers> _trueTurnovers;

        /// <summary>
        /// Коллекция населённых пунктов
        /// </summary>
        public static List<v_Settlements> VSettlements
        {
            get
            {


                if (_VSettlements == null)
                    _VSettlements = Entities.v_Settlements.ToList();
                return _VSettlements;
            }
        }


        /// <summary>
        /// Текущий язык в системе
        /// </summary>
        public static CurrentLanguage CurrentLanguage
        {
            get
            {
                string culture = Thread.CurrentThread.CurrentCulture.ToString();
                if (culture.Contains("ru"))
                {
                    return CurrentLanguage.Russian;
                }
                else
                {
                    return CurrentLanguage.English;
                }
            }
        }

        /// <summary>
        /// Сохранение изменений
        /// </summary>
        /// <returns></returns>
        public static bool Save()
        {
            try
            {
             //   Entities.Configuration.AutoDetectChangesEnabled = false;
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                return false;
            }
            finally
            {
               // Entities.Configuration.AutoDetectChangesEnabled = true;
            }
            return true;
        }

       

        /// <summary>
        /// Удаление объекта
        /// </summary>
        /// <typeparam name="E">Класс</typeparam>
        /// <param name="entity">Объект</param>
        /// <returns>Результат операции</returns>
        public static bool Delete<E>(E entity) where E : class
        {
           try
           {
               Entities.Configuration.AutoDetectChangesEnabled = false;
               Entities.Entry(entity).State = EntityState.Deleted;
               Entities.Configuration.AutoDetectChangesEnabled = true;
               return Save();
           }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Добавление элемента
        /// </summary>
        /// <typeparam name="E">Класс элемента</typeparam>
        /// <param name="entity">Элемент</param>
        /// <param name="userLogin">Имя пользователя, который вносит изменения</param>
        /// <returns>Результат операции</returns>
        public static bool Add<E>(E entity, string userLogin) where E : class
        {
            Entities.Configuration.AutoDetectChangesEnabled = false;
            SetChangedUser(entity, userLogin);

            Entities.Entry(entity).State = EntityState.Added;
            Entities.Configuration.AutoDetectChangesEnabled = true;
            return Save();
        }


       

        /// <summary>
        /// Установка пользователя, который внёс изменения
        /// </summary>
        /// <param name="item">Измененённый элемент</param>
        /// <param name="userLogin">Пользователь</param>
        internal static void SetChangedUser(object item, string userLogin)
        {
            var setChangedUserInterface = item as ISetChangedUser;

            if (setChangedUserInterface != null)
            {
                setChangedUserInterface.SetChangedUser(userLogin);
            }
        }

        /// <summary>
        /// Обновление элемента
        /// </summary>
        /// <typeparam name="E">Класс</typeparam>
        /// <param name="entity">Элемент</param>
        /// <param name="userLogin">Пользователь</param>
        /// <returns>Результат операции</returns>
        public static bool Update<E>(E entity, string userLogin) where E : class
        {
            SetChangedUser(entity, userLogin);
            Entities.Configuration.AutoDetectChangesEnabled = false;

            Entities.Entry(entity).State = EntityState.Modified;
            Entities.Configuration.AutoDetectChangesEnabled = true;
            return Save();
        }



       
//        #region Turnovers

//        private static List<Turnovers> turnovers; 

//        public static List<Turnovers> Turnovers
//        {
//            get
//            {
//                if (turnovers == null)
//                {
//                    turnovers = Entities.Turnovers.ToList();
//                }

//                    return turnovers;
//            }
//        } 

//#endregion

//#region Users

//        private static List<Users> _users; 

//        /// <summary>
//        /// Пользователи
//        /// </summary>
//        public static List<Users> Users
//        {
//            get
//            {
//                if(_users==null)
//                { _users= Entities.Users.OrderBy(c => c.UserFullNameRu).ToList(); }
//                return _users;
//            }
//        } 

//#endregion


        //#region Dialers


        ///// <summary>
        ///// Дилеры
        ///// </summary>
        //private static List<Customers> _dealers;

        ///// <summary>
        ///// Дилеры
        ///// </summary>
        //public static List<Customers> Dealers
        //{
        //    get
        //    {
        //        if (_dealers == null)
        //        {
        //            var col = new CustomersCollection();

        //            var result = new List<Customers>();

        //            var dealersNumbers = new[]
        //                                     {
        //                                         450, 861, 221, 432, 435, 456, 1593, 422, 1529, 5179, 1279, 1121, 426, 4311
        //                                         , 4249, 4257, 4832, 156, 900, 4249, 861, 7459, 6064, 458, 5118, 7502, 1401
        //                                         , 7699, 4257, 7699, 4257, 7557, 7828, 8450, 8615, 4257, 7675, 7828, 4307
        //                                     };


        //            foreach (int number in dealersNumbers)
        //            {
        //                Customers cust =col.GetCustomerBySequentalNumber(number);
        //                if (cust != null)
        //                    if (!result.Contains(cust))
        //                        result.Add(cust);
        //            }


        //            _dealers = result;
        //        }
        //        return _dealers;
        //    }
        //}

        //#endregion

        //#region Products


        ///// <summary>
        ///// Продукты
        ///// </summary>
        //private static List<Products> _products;


        ///// <summary>
        ///// Продукты
        ///// </summary>
        //public static List<Products> Products
        //{
        //    get
        //    {
        //        if(_products==null)
        //        {
        //            _products = DB.Entities.Products.ToList();
        //        }
        //       return  _products;
        //    }
        //}

        ///// <summary>
        ///// Марки продуктов
        ///// </summary>
        //private static List<ProductMarks> _productMarks;


        ///// <summary>
        ///// Марки продуктов
        ///// </summary>
        //public static List<ProductMarks> ProductMarks
        //{
        //    get
        //    {
        //        if(_productMarks==null)
        //            _productMarks = Entities.ProductMarks.ToList();
        //        return _productMarks;
        //    }

        //}

        //#endregion
    }
}